<?php
namespace app\api\controller;
use think\Controller;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\Request;
use think\response\Json;

/**
 * Class Wechat
 * @package app\api\controller
 * 凡是带有【三合一】说明是失主、失物、宠物功能的共同接口
 */

class Wechat extends Controller{

    public $appid="wx424f2567ec57554c";
    public $secret="80560dd35c137161a945f4bfae9e8938";
    public $qq_appid="1111996685";
    public $qq_secret="gXGzVQjg5lVZsi6U";


    /**
     * 获取微信AccessToken
     * @return mixed 微信的AccessToken
     */
    private function getAccessToken()
    {
        if (session('?token'))
        {
            $access_token=session('token');
        }else{
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->secret}";
            $html = file_get_contents($url);
            $output = json_decode($html, true);

            $access_token = $output['access_token'];

            session('token',$access_token);
        }


        return $access_token;
    }


    /**
     * curl模拟POST提交
     * @param $url string 要发送的链接
     * @param $data array 要发送的数据
     * @return array 回调数据
     */
    protected function curlPost($url,$data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST,true);
        curl_setopt($ch, CURLOPT_POSTFIELDS,  json_encode($data,true));
        $content = curl_exec($ch); //执行
        curl_close($ch); //关闭连接
        return json_decode($content,true);
    }

    public function sendSubscribeMessage($uid, $data, $page='pages/index/index', $template_id="Sueyftu96Vyw0W30L26ucHezkcIk9-WR8Ao1rVihTdA") //发送模板消息
    {
        $UserData=\db('users')->where('Id',$uid)->find();

        $access_token=$this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={$access_token}";

        $send_data=[
            'touser'=>$UserData['wx_openid'],
            'template_id'=>$template_id,
            'page'=>$page,
            'data'=>$data,
            'miniprogram_state' => 'formal',
        ];
        if ($UserData['wx_openid']!='')
            return $this->curlPost($url,$send_data);
        else
            return ['result'=>'error','msg'=>'你没有绑定小程序'];
    }

    /**
     * 随机获取数据
     * @param int $num 获取数量
     * @param string $table 表名
     * @param array $where 查询方式
     * @param string $field 查询字段
     * @param array $order  排序方式
     * @param string $pk  统计使用的字段
     * @return array|\PDOStatement|string|\think\Collection|\think\model\Collection
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    private function random_data($num, $table, $where = [], $field = '*', $order = [], $pk = 'Id')//随机获取数据
    {
        $countcus = db($table)
            ->field($pk)
            ->where($where)
            ->select();
        if (count($countcus) == 0) {
            return [];
        }
        $arr = [];
        $flag = 0;
        $countnum = count($countcus);
        if ($countnum < $num) {
            $num = $countnum;
        }
        for ($i = 0; $i < $num; $i++) {
            $randnum = $countcus[mt_rand(0, $countnum - 1)][$pk];
            if ($flag != $randnum) {
                if (!in_array($randnum, $arr)) {
                    $arr[] = $randnum;
                    $flag = $randnum;
                } else {
                    $i--;
                }
            }else{
                $i--;
            }
        }
        $list = db($table)
            ->field($field)
            ->where($pk, 'in', $arr)
            ->order('time','desc')
            ->select();
        return $list;
    }

    /**
     * 发送激活邮件
     * @param $username String 发送者的用户名
     * @param $qq String 发送者的QQ
     * @param $ActiveCode  String 激活码
     * @throws \PHPMailer\PHPMailer\Exception
     */
    private function SendActiveMail($username,$qq,$ActiveCode)   //发送激活邮件
    {

        $tomail=$qq.'@qq.com';
        $body= 'https://'.$_SERVER['HTTP_HOST'].'/Index/Reg/Verify.html?qq='.$qq.'&ActiveCode='.$ActiveCode;
        $body="亲爱的同学，你已经完成了湖工志愿平台的注册，您的账号为<br>\n".$username."<br>\n，接下来需要您来激活以确认你是真人，请点击以下链接激活：\n<br><a href='".$body."'>".$body."</a>";
        send_mail($tomail,'同学','注册成功！请激活',$body);
    }


    /**
     * 获取网站配置信息
     * @return Json 网站配置的Json对象
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function WebConfig() //网站配置信息
    {
        $WebData=\db('config')->select();
        $Return=[];
        foreach ($WebData as $webDatum)
        {
            if ($webDatum['key']!='mail_password')
                $Return[$webDatum['key']]=$webDatum['value'];
        }
        return json($Return);
    }

    /**
     * 微信登录接口
     * @return Json 返回包括SafeCode的Json对象
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     * @throws \PHPMailer\PHPMailer\Exception
     * @throws PDOException
     */
    public function Login()
    {
        //获取登录的表单数据
        $data=input('param.');

        //获取登录传进的验证码
        $code=$data['code'];

        //请求获取动态码
        $request=file_get_contents("https://api.weixin.qq.com/sns/jscode2session?appid={$this->appid}&secret={$this->secret}&js_code={$code}&grant_type=authorization_code");
        $res=json_decode($request,true);

        //获取微信用户唯一标识码
        $openid=$res['openid'];

        //通过标识码获取用户信息
        $UserData=db('users')->where('wx_openid',$openid)->find();

        //信息不存在，则未绑定账号
        if (empty($UserData))
        {

            return json(['status'=>0,'msg'=>'还未绑定账号','openid'=>$openid,'result'=>'error']);

        }else{

            //未激活
            if ($UserData['active']==0)
            {
                //更新激活码并发送
                $ActiveCode=GetRandStr(20);
                Db::name('users')->where('qq',$UserData['qq'])->update(['ActiveCode'=>$ActiveCode]);
                $this->SendActiveMail($UserData['username'],$UserData['qq'],$ActiveCode);

                //返回错误信息
                return json(['status'=>2,'openid'=>$openid,'msg'=>'您的账号还未激活','result'=>'error']);
            }


            $SafeCode=$UserData['SafeCode'];

            Monitor('使用微信成功登录!',$SafeCode);

            if ($UserData['phone']==''||$UserData['name']==''||$UserData['college']==''||$UserData['phone']==null||$UserData['name']==null||$UserData['college']==null)
            //引导用户编辑个人信息
            {
                return json(['status'=>1,'SafeCode'=>$SafeCode,'openid'=>$openid,'result'=>'success','edit'=>1]);
            }
            return json(['status'=>1,'SafeCode'=>$SafeCode,'openid'=>$openid,'result'=>'success']);
        }
    }

    public function qqLogin() //qq登录接口，返回SafeCode
    {
        $data=input('param.');
        $code=$data['code'];

        $request=file_get_contents("https://api.q.qq.com/sns/jscode2session?appid={$this->qq_appid}&secret={$this->qq_secret}&js_code={$code}&grant_type=authorization_code");
        $res=json_decode($request,true);
        $openid=$res['openid'];

        $UserData=db('users')->where('qq_openid',$openid)->find();
        if (empty($UserData))
            return json(['status'=>0,'msg'=>'还未绑定账号','openid'=>$openid,'result'=>'error']);
        else{
            if ($UserData['active']==0)
            {
                $ActiveCode=GetRandStr(20);
                Db::name('users')->where('qq',$UserData['qq'])->update(['ActiveCode'=>$ActiveCode]);
                $this->SendActiveMail($UserData['username'],$UserData['qq'],$ActiveCode);
                return json(['status'=>2,'openid'=>$openid,'msg'=>'您的账号还未激活','result'=>'error']);
            }


            $SafeCode=$UserData['SafeCode'];
            Monitor('使用微信成功登录!',$SafeCode);
            return json(['status'=>1,'SafeCode'=>$SafeCode,'openid'=>$openid,'result'=>'success']);
        }
    }

    public function bind()  //绑定接口
    {
        $data=input('param.');
        $openid=$data['openid'];
        $username=$data['username'];
        $pwd=$data['pwd'];
        if ($openid=='')
        {
            return json(['result'=>'error','msg'=>'微信信息获取失败']);
        }
        if ($username=='')
            return json(['result'=>'error','msg'=>'请输入账号']);
        if ($pwd=='')
            return json(['result'=>'error','msg'=>'请输入密码']);

        $user=db('users')->where(['username'=>$username,'password'=>md5($pwd)])->find();


        $userByOpenid=\db('users')->where('wx_openid',$openid)->find();
        if (!empty($userByOpenid))
            return json(['result'=>'error','msg'=>'此微信已被绑定']);

        if (!empty($user))
        {
            if($user['active']==0)
                return json(['result'=>'error','msg'=>'账号还未激活，请重新前往邮箱激活']);
            else{
                $SafeCode=GetRandStr(20);
                db('users')->where(['username'=>$username,'password'=>md5($pwd)])->update(['SafeCode'=>$SafeCode,'wx_openid'=>$openid]);
                Monitor('绑定了微信!',$SafeCode);
                return json(['result'=>'success','status'=>1,'SafeCode'=>$SafeCode,'msg'=>'绑定成功']);
            }
        }else{
            $confirm=\db('users')->where('username',$username)->find();
            if (!empty($confirm))       //如果存在账号，但是密码不对
                return json(['result'=>'error','msg'=>'存在账号，密码错误']);
            else{       //不存在账号就顺便注册
                $qq=input('param.qq');
                if ($qq=='')
                    return json(['result'=>'error','msg'=>'请先输入qq']);
                $SQL=\db('users')->insert(['username'=>$username,'password'=>md5($pwd),'qq'=>$qq,'wx_openid'=>$openid]);
                if ($SQL)
                {
                    $ActiveCode=GetRandStr(20);
                    Db::name('users')->where('qq',$qq)->update(['ActiveCode'=>$ActiveCode]);
                    $this->SendActiveMail($username,$qq,$ActiveCode);
                    return json(['result'=>'success','msg'=>'注册成功,请前往邮箱绑定账号后重新进入小程序，在绑定成功前，您的账号是无效的']);
                }
            }
        }


    }

    public function qqbind()  //qq绑定接口
    {
        $data=input('param.');
        $openid=$data['openid'];
        $username=$data['username'];
        $pwd=$data['pwd'];
        if ($openid=='')
        {
            return json(['result'=>'error','msg'=>'微信信息获取失败']);
        }
        if ($username=='')
            return json(['result'=>'error','msg'=>'请输入账号']);
        if ($pwd=='')
            return json(['result'=>'error','msg'=>'请输入密码']);

        $user=db('users')->where(['username'=>$username,'password'=>md5($pwd)])->find();


        $userByOpenid=\db('users')->where('qq_openid',$openid)->find();
        if (!empty($userByOpenid))
            return json(['result'=>'error','msg'=>'此微信已被绑定']);

        if (!empty($user))
        {
            if($user['active']==0)
                return json(['result'=>'error','msg'=>'账号还未激活，请重新前往邮箱激活']);
            else{
                $SafeCode=GetRandStr(20);
                db('users')->where(['username'=>$username,'password'=>md5($pwd)])->update(['SafeCode'=>$SafeCode,'qq_openid'=>$openid]);
                Monitor('绑定了微信!',$SafeCode);
                return json(['result'=>'success','status'=>1,'SafeCode'=>$SafeCode,'msg'=>'绑定成功']);
            }
        }else{
            $confirm=\db('users')->where('username',$username)->find();
            if (!empty($confirm))       //如果存在账号，但是密码不对
                return json(['result'=>'error','msg'=>'存在账号，密码错误']);
            else{       //不存在账号就顺便注册
                $qq=input('param.qq');
                if ($qq=='')
                    return json(['result'=>'error','msg'=>'请先输入qq']);
                $SQL=\db('users')->insert(['username'=>$username,'password'=>md5($pwd),'qq'=>$qq,'qq_openid'=>$openid]);
                if ($SQL)
                {
                    $ActiveCode=GetRandStr(20);
                    Db::name('users')->where('qq',$qq)->update(['ActiveCode'=>$ActiveCode]);
                    $this->SendActiveMail($username,$qq,$ActiveCode);
                    return json(['result'=>'success','msg'=>'注册成功,请前往邮箱绑定账号后重新进入小程序，在绑定成功前，您的账号是无效的']);
                }
            }
        }


    }

    public function UserInfo()  //用户信息接口
    {
        $SafeCode=input('param.SafeCode');
        $UserInfo=\db('users')->where('SafeCode',$SafeCode)->find();
        if(empty($UserInfo))
        {
            return json(['result'=>'error','msg'=>'没有此用户']);
        }
        $UserInfo['help_num']=\db('message')->where('uid',$UserInfo['Id'])->count();
        $UserInfo['comment_num']=\db('bbs')->where('uid',$UserInfo['Id'])->count();
        $UserInfo['thing_num']=\db('find_radar')->where('uid',$UserInfo['Id'])->count();
        $UserInfo['pet_num']=\db('pet')->where('uid',$UserInfo['Id'])->count();
        $departList=\db('depart')->select();
        $collegeList=\db('college')->select();
        $majorList=\db('major')->select();

        $Sid=\db('sid')->where('uid',$UserInfo['Id'])->find();

        if (!empty($Sid))
        {
            $UserInfo['Sid_sid']=$Sid['sid'];
            $UserInfo['Sid_pwd']=$Sid['pwd'];
        }


        foreach ($departList as $list)
            $UserInfo['departList'][]=$list['depart'];

        foreach ($majorList as $list)
            $UserInfo['majorList'][]=$list['major_name'];

        foreach ($collegeList as $list)
            $UserInfo['collegeList'][]=$list['college_name'];

        $UserInfo['USER_PIC']="https://q1.qlogo.cn/g?b=qq&nk={$UserInfo["qq"]}&s=160";
        return json($UserInfo);
    }

    /**
     * app更新
     * @throws DataNotFoundException
     * @throws DbException
     * @throws PDOException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public function androidEditDetail(): Json    //编辑信息
    {
        $data=input('post.userInfo');
        $SafeCode=input('post.SafeCode');
        $update=[
            'name'=>$data['name'],
            'sex'=>$data['sex'],
            'college'=>$data['college'],
            'major'=>$data['major'],
            'phone'=>$data['phone'],
            'department'=>$data['department']
        ];

        if (!isset($SafeCode)||$SafeCode==''){
            return json(['result'=>'error','msg'=>'修改失败']);
        }

        \db()->startTrans();

        try{

            //更新教务系统信息
            if(isset($data['Sid_sid'])&&isset($data['Sid_pwd']))
            {
                if ($data['Sid_sid']!='' && $data['Sid_pwd']!='')
                {
                    $User=\db('users')->where('SafeCode',$SafeCode)->find();
                    $uid=$User['Id'];

                    $sid=$data['Sid_sid'];
                    $pwd=$data['Sid_pwd'];

                    $Sid=\db('sid')->where('uid',$uid)->find();



                    if(empty($Sid)){
                        //没有就添加教务系统账号
                        \db('sid')->insert([
                            'sid'=>$sid,
                            'pwd'=>$pwd,
                            'uid'=>$uid,
                        ]);
                    }else{
                        //防止重复更新
                        if($Sid['pwd']!=$pwd){
                            //有就更新
                            \db('sid')->where('uid',$uid)->update([
                                'sid'=>$sid,
                                'pwd'=>$pwd
                            ]);
                        }

                    }

                }
            }

            //更新其他信息
            db('users')->where('SafeCode',$SafeCode)->update($update);

            return json(['result'=>'success']);

        }catch (\Exception $e){

            db()->rollback();

            return json(['result'=>'error','msg'=>'修改失败']);
        }

    }

    public function editDetail()    //编辑信息
    {
        $complete=false;
        $data=input('post.');
        $update=[
            'name'=>$data['name'],
            'sex'=>$data['sex'],
            'college'=>$data['college'],
            'major'=>$data['major'],
            'phone'=>$data['phone'],
            'department'=>$data['department']
        ];


        if(isset($data['Sid_sid'])&&isset($data['Sid_pwd']))
        {
            if ($data['Sid_sid']!='' && $data['Sid_pwd']!='')
            {
                $User=\db('users')->where('wx_openid',$data['wx_openid'])->find();
                $uid=$User['Id'];

                $sid=$data['Sid_sid'];
                $pwd=$data['Sid_pwd'];

                $Sid=\db('sid')->where('uid',$uid)->find();
                if(empty($Sid)) //没有就添加教务系统账号
                    $SQL1=\db('sid')->insert([
                        'sid'=>$sid,
                        'pwd'=>$pwd,
                        'uid'=>$uid,
                    ]);
                else    //有就更新
                    $SQL1=\db('sid')->where('uid',$uid)->update([
                        'sid'=>$sid,
                        'pwd'=>$pwd
                    ]);

                if ($SQL1)
                    $complete=true;
                else
                    $complete=false;

            }
        }

        $SQL2=\db('users')->where('wx_openid',$data['wx_openid'])->update($update);
        if ($SQL2||$complete)
            return json(['result'=>'success']);
        else
            return json(['result'=>'error','msg'=>'修改失败']);
    }

    public function CommentJson(): Json   //留言信息接口
    {
        $Bbs=\db('bbs')->alias('b')
            ->order("time","desc")
            ->limit(20)->select();
        foreach ($Bbs as $key=>$bbs)
        {
            $Bbs[$key]['AvatarUrl']="https://q1.qlogo.cn/g?b=qq&nk={$bbs['qq']}&s=160";
            $Bbs[$key]['CommentList']=\db('comment')->order("time","desc")->where('Upper',$bbs['Id'])->select();
            $Bbs[$key]['num']=0;
            foreach ($Bbs[$key]['CommentList'] as $key2=>$comment)
            {
                $Bbs[$key]['CommentList'][$key2]['AvatatUrl']="https://q1.qlogo.cn/g?b=qq&nk={$comment['qq']}&s=160";
                $Bbs[$key]['num']++;
            }
        }
        return json($Bbs);
    }

    public function MyComment(): Json //我的留言接口
    {
        $SafeCode=input('post.SafeCode');
        $uid=\db('users')->where('SafeCode',$SafeCode)->field('Id')->find()['Id'];
        $Comments=\db('bbs')->where('uid',$uid)->order('time','desc')->select();
        foreach ($Comments as $key=>$comment)
        {
            $Comments[$key]['AvatarUrl']="https://q1.qlogo.cn/g?b=qq&nk={$comment['qq']}&s=160";
        }
        return json($Comments);
    }

    public function CommentSend(): Json   //发布留言
    {

        $content=input('post.Comment');
        $SafeCode=input('post.SafeCode');
        $content=nl2br($content);
        if ($content==''||$SafeCode==''||!isset($content)||!isset($SafeCode))
            return json(['result'=>'error','msg'=>'发表失败']);
        $UserData=\db('users')->where('SafeCode',$SafeCode)->find();
        if (empty($UserData))
            return json(['result'=>'error','msg'=>'请重新登录']);
        $insert=[
            'name'=>$UserData['name'],
            'qq'=>$UserData['qq'],
            'content'=>$content,
            'time'=>date("Y-m-d H:i:s",time()),
            'uid'=>$UserData['Id']
        ];

        if (\db('bbs')->insert($insert))
            return json(['result'=>'success','msg'=>'发布成功']);
        else
            return json(['result'=>'error','msg'=>'发表失败']);
    }

    public function ReplySend(): Json    //发表评论
    {
        $content=input('post.content');
        $content=nl2br($content);
        $SafeCode=input('post.SafeCode');
        $comment_id=input('post.comment_id');

        if ($content==''||$SafeCode==''||$comment_id==''||!isset($content)||!isset($SafeCode)||!isset($comment_id))

            return json(['result'=>'error','msg'=>'发表失败']);
        $UserData=\db('users')->where('SafeCode',$SafeCode)->find();
        if (empty($UserData))
            return json(['result'=>'error','msg'=>'请重新登录']);


        //20210811 新增收到评论会收到小程序提醒

        $data=[
            "thing1"=>[
                'value'=>$UserData['name']
            ],
            "time2"=>[
                'value'=>date('Y-m-d H:i:s',time())
            ],
            "thing3"=>[
                'value'=>$content
            ],
            "phrase4"=>[
                'value'=>'未回复'
            ],
            "thing5"=>[
                'value'=>'对你的留言进行了评论'
            ],
        ];

        $uid=\db('bbs')->where('Id',$comment_id)->value('uid');

        $this->sendSubscribeMessage($uid,$data);

        $insert=[
            'name'=>$UserData['name'],
            'qq'=>$UserData['qq'],
            'content'=>$content,
            'time'=>date("Y-m-d H:i:s",time()),
            'Upper'=>$comment_id,
            'uid'=>$UserData['Id']
        ];
        $SQL=\db('comment')->insert($insert);
        if ($SQL)
            return json(['result'=>'success','msg'=>'发布成功']);
        else
            return json(['result'=>'error','msg'=>'发表失败']);
    }

    public function WishJson(): Json  //许愿信息接口
    {
        $Data=$this->random_data(10,'wall');

        return json($Data);
    }

    public function WishSend(): Json  //许愿发送
    {
        $content=input('post.Wish');
        $SafeCode=input('post.SafeCode');
        $NickName=input('post.NickName');
        $content=nl2br($content);
        if ($content==''||$SafeCode==''||!isset($content)||!isset($SafeCode))
            return json(['result'=>'error','msg'=>'发表失败']);
        $UserData=\db('users')->where('SafeCode',$SafeCode)->find();
        if (empty($UserData))
            return json(['result'=>'error','msg'=>'请重新登录']);
        $insert=[
            'nickname'=>$NickName,
            'content'=>$content,
            'time'=>date("Y-m-d H:i:s",time()),
        ];

        if (\db('wall')->insert($insert))
            return json(['result'=>'success','msg'=>'发布成功']);
        else
            return json(['result'=>'error','msg'=>'发表失败']);
    }

    public function PersonList(): Json    //可发件人列表
    {
        $toMail=[];
        $toMail[]=[
            'value'=>0,
            'name'=>'全体青协',
            'checked'=>false,
            'hot'=>false,
        ];

        //各院青协
        $College=db("college")->select();

        foreach ($College as $key=>$item)
        {

            $toMail[]=[
                'value'=>$item['Id'],
                'name'=>$item["college_name"]."-青协",
                'checked'=>false,
                'hot'=>false,
            ];
        }
        return json($toMail);
    }

//    public function SendHelpByAndroid(){
//        $title=input("post.title");
//        $content=input('post.content');
//        $SafeCode=input('post.SafeCode');
//        $toMail=input('post.Person');
//
//        //判断登录状态
//        if (!isset($SafeCode)||$SafeCode==''){
//            return json(["result"=>'error',"msg"=>"请重新进入app以登录"]);
//        }
//
//        //获取发件人信息
//        $PersonData=Db::name('users')->where('SafeCode',$SafeCode)->find();
//        $fromUser=$PersonData["name"];
//        $uid=$PersonData["Id"];
//
//        //获取随机码
//        $randCode=GetRandStr(20);
//
//        //限制每日发件数量
//        $count=\db('message')
//            ->group('code')
//            ->where('uid',$uid)
//            ->whereTime('time','>=',date('Y-m-d'))
//            ->whereTime('time','<',date('Y-m-d',time()+24*3600))
//            ->count();
//
//        if ($count>=C('limit_msg')  && in_array($PersonData['auth'],[5,0])) {
//            return json(["result"=>'error',"msg"=>"每日只能发送".C('limit_msg')."条信息"]);
//        }
//
//        //将发件信息存入数据库并返回id
//        $MsgId=Db::name('message')->insertGetId([
//            'title'=>$title,
//            'content'=>$content,
//            'fromUser'=>$fromUser,
//            'time'=>date('Y-m-d H:i:s',time()),
//            'qq'=>$PersonData["qq"],
//            'uid'=>$uid,
//            'code'=>$randCode
//        ]);
//
//        if(input('post.Person.name')){
//
//        }
//
//    }

    public function SendHelp(): Json  //发送求助信息
    {
        $title=input("post.title");
        $content=input('post.content');
        $SafeCode=input('post.SafeCode');
        $toMail=input('post.Person');
        $content=nl2br($content);
        if (!isset($SafeCode)||$SafeCode==''){
            return json(["result"=>'error',"msg"=>"请重新进入小程序以登录"]);
        }

        //获取发件人信息
        $PersonData=Db::name('users')->where('SafeCode',$SafeCode)->find();
        $fromUser=$PersonData["name"];
        $uid=$PersonData["Id"];
        $randCode=GetRandStr(20);   //获取随机码

        //限制每日发件数量
        $count=\db('message')
            ->group('code')
            ->where('uid',$uid)
            ->whereTime('time','>=',date('Y-m-d'))
            ->whereTime('time','<',date('Y-m-d',time()+24*3600))
            ->count();

        if ($count>=C('limit_msg')  && in_array($PersonData['auth'],[5,0]))
            return json(["result"=>'error',"msg"=>"每日只能发送".C('limit_msg')."条信息"]);

        //将发件信息存入数据库
        $MsgId=Db::name('message')->insertGetId([
            'title'=>$title,
            'content'=>$content,
            'fromUser'=>$fromUser,
            'time'=>date('Y-m-d H:i:s',time()),
            'qq'=>$PersonData["qq"],
            //20210725 新增加入用户id
            'uid'=>$uid,
            'code'=>$randCode
        ]);

        $all=false;

        $Ids=[];
        foreach ($toMail as $oneToMail)
        {
            //如果选中了全体青协
            if ($oneToMail['value']==0 && $oneToMail['checked']==true)
            {
                $all=true;
                break;
            }else{
                if ($oneToMail['checked']==true)
                {

                    //选中的学院的id集合
                    $Ids[]=$oneToMail['value'];

                }

            }
        }

        if ($all)
        {
            $UserData=db('users')->where('auth','<>',0)->select();
        }else{
            $UserData=\db('users')
                ->alias('u')
                ->join('wyz_college c','c.college_name=u.college')
                ->field('u.*')
                ->where('c.Id','in',$Ids)
                ->select();
        }



        $Users=[];
        foreach ($UserData as $UserDatum)
        {
            $datum=[
                "username"=>$UserDatum["username"],
                "qq"=>$UserDatum["qq"],
                "name"=>$UserDatum["name"],
                "Id"=>$UserDatum["Id"]
            ];
            $Users[]=$datum;
        }


        //发送给小程序的信息
        $wx_content=$content;

        $content=$content."<br><br><br>".
            "\n请求人信息：<br>\n".
            "<p>用户名：".$fromUser."</p>\n".
            "<p>QQ:".$PersonData["qq"]."</p>\n".
            "<p>电话：".$PersonData['phone']."</p>\n".
            "<p>学院：".$PersonData["college"]."</p>\n".
            "<p>专业：".$PersonData["major"]."</p>\n";

        $data=[
            "thing1"=>[
                'value'=>$fromUser
            ],
            "time2"=>[
                'value'=>date('Y-m-d H:i:s',time())
            ],
            "thing3"=>[
                'value'=>$wx_content
            ],
            "phrase4"=>[
                'value'=>'未解决'
            ],
            "thing5"=>[
                'value'=>'标题：'.$title
            ],
        ];

        $success=0;
        $error=0;
        foreach ($Users as $user)   //发件
        {
            //尝试发件
            try {

                $this->sendSubscribeMessage($user['Id'],$data);
                send_mail($user["qq"]."@qq.com",$user["name"],$title,$content);

                //新增未读邮件
                db('msg_read')->insert([
                    'message_id'=>$MsgId,
                    'read'=>false,
                    'uid'=>$user["Id"]
                ]);
            }catch (\Exception $e){
                $error++;
            }

            $success++;
        }
        Monitor('使用了求助功能',$SafeCode);

        return json(["result"=>"success","msg"=>"发送完成"]);
    }

    public function MyHelp(): Json    //我的求助接口
    {
        $SafeCode=input('post.SafeCode');
        $uid=\db('users')->where('SafeCode',$SafeCode)->field('Id')->find()['Id'];
        $Helps=\db('message')->where('uid',$uid)->order('time','desc')->select();
        foreach ($Helps as $key=>$help)
        {
            $Helps[$key]['AvatarUrl']="https://q1.qlogo.cn/g?b=qq&nk={$help['qq']}&s=160";
        }
        return json($Helps);
    }

    public function thingList(): Json //失物列表
    {
        if(input('post.search')&&input('post.search')!='')
        {
            $search=input('post.search');

            //是否是标签搜索
            if(strstr($search, 'tag:'))
            {
                //获取搜索的标签
                $tag=explode("tag:",$search)[1];
                $Things=db('find_radar')->alias('a')
                    ->group('a.Id')
                    ->field('a.*')
                    ->join('wyz_radar_tag b','a.Id=b.radar_id')
                    ->where('a.thing','1')
                    ->join('wyz_tag t','b.tag_id=t.Id')
                    ->where('t.tag_name',$tag)
                    ->order('a.time','desc')
                    ->select();

            }else{

                $where=[
                    ['title','like','%'.$search.'%'],
                    ['content','like','%'.$search.'%']
                ];

                $Things=\db('find_radar')
                    ->where(function ($query)use($where){
                        $query->whereOr($where);
                    })->where(function ($query){
                        $query->where('thing','1');
                    })->order('time','asc')->select();
            }

        }else{
            //审核完改回来
            if (input('get.SafeCode'))
            {
                $uid=\db('users')->where('SafeCode',input('get.SafeCode'))->value('Id');
                $Things=\db('find_radar')->where('thing','1')->where('uid',$uid)->order('time','desc')->select();
            }
            else
                $Things=\db('find_radar')->where('thing','1')->order('time','desc')->select();

        }

        foreach ($Things as $key=>$thing)
        {
            $thingId=$thing['Id'];
            $tag_list=\db('radar_tag')->alias('a')
                ->join('wyz_tag b','a.tag_id=b.Id')
                ->where('a.radar_id',$thingId)
                ->field('b.tag_name')
                ->select();

            //获取其对应的图片数据
            $img=\db('find_img')->where('code',$thing['code'])->find();
            if (!empty($img))
            {
                $Things[$key]['hasImg']=1;
                $Things[$key]['ImgUrl']="https://{$_SERVER['HTTP_HOST']}/{$img['url']}";
            }

            $tag_name_list=[];
            foreach ($tag_list as $item)
            {
                $tag_name_list[]=$item['tag_name'];
            }
            if (!empty($tag_name_list))
                $Things[$key]['tags']=$tag_name_list;
        }
        return json($Things);
    }

    public function masterList(): Json //失主列表
    {
        if(input('post.search')&&input('post.search')!='')
        {
            $search=input('post.search');

            //是否是标签搜索
            if(strstr($search, 'tag:'))
            {
                //获取搜索的标签
                $tag=explode("tag:",$search)[1];
                $Masters=db('find_radar')->alias('a')
                    ->group('a.Id')
                    ->field('a.*')
                    ->join('wyz_radar_tag b','a.Id=b.radar_id')
                    ->where('a.master','1')
                    ->join('wyz_tag t','b.tag_id=t.Id')
                    ->where('t.tag_name',$tag)
                    ->order('a.time','desc')
                    ->select();

            }else{

                $where=[
                    ['title','like','%'.$search.'%'],
                    ['content','like','%'.$search.'%']
                ];

                $Masters=\db('find_radar')
                    ->where(function ($query)use($where){
                        $query->whereOr($where);
                    })->where(function ($query){
                        $query->where('master','1');
                    })->order('time','asc')->select();
            }

        }else{
            //审核完改回来
            if (input('get.SafeCode'))
            {
                $uid=\db('users')->where('SafeCode',input('get.SafeCode'))->field('Id')->find()['Id'];
                $Masters=\db('find_radar')->where('master','1')->where('uid',$uid)->order('time','desc')->select();
            }
            else
                $Masters=\db('find_radar')->where('master','1')->order('time','desc')->select();

        }

        foreach ($Masters as $key=>$master)
        {
            $masterId=$master['Id'];
            $tag_list=\db('radar_tag')->alias('a')
                ->join('wyz_tag b','a.tag_id=b.Id')
                ->where('a.radar_id',$masterId)
                ->field('b.tag_name')
                ->select();

            //获取其对应的图片数据
            $img=\db('find_img')->where('code',$master['code'])->find();
            if (!empty($img))
            {
                $Masters[$key]['hasImg']=1;
                $Masters[$key]['ImgUrl']="https://{$_SERVER['HTTP_HOST']}/{$img['url']}";
            }

            $tag_name_list=[];
            foreach ($tag_list as $item)
            {
                $tag_name_list[]=$item['tag_name'];
            }
            if (!empty($tag_name_list))
                $Masters[$key]['tags']=$tag_name_list;
        }
        return json($Masters);
    }

    public function petList(): Json //宠物列表
    {
        if(input('post.search')&&input('post.search')!='')
        {
            $search=input('post.search');

            $where=[
                ['name','like','%'.$search.'%'],
                ['varieties','like','%'.$search.'%'],
                ['description','like','%'.$search.'%']
            ];

            $Pets=\db('pet')
                ->where(function ($query)use($where){
                    $query->whereOr($where);
                })->order('time','desc')->select();


        }else{
            //审核完改回来
            if (input('get.SafeCode'))
            {
                $uid=\db('users')->where('SafeCode',input('get.SafeCode'))->field('Id')->find()['Id'];
                $Pets=\db('pet')->where('uid',$uid)->order('time','desc')->select();
            }
            else
                $Pets=\db('pet')->order('time','desc')->select();

        }

        foreach ($Pets as $key=>$pet)
        {
            $petId=$pet['Id'];
            //获取其对应的图片数据
            $img=\db('find_img')->where('code',$pet['code'])->find();
            if (!empty($img))
            {
                $Pets[$key]['hasImg']=1;
                $Pets[$key]['ImgUrl']="https://{$_SERVER['HTTP_HOST']}/{$img['url']}";
            }
        }
        return json($Pets);
    }

    public function Detail(): Json    //详情信息
    {
        $Id=input('post.id');

        if (input('post.type')=='pet')
        {
            $Pet=\db('pet')
                ->alias('p')
                ->join('wyz_users u','u.Id=p.uid')
                ->field('p.*,u.qq,u.phone')
                ->where('p.Id',$Id)->find();

            $code=$Pet['code'];

            $Images=\db('find_img')->where('code',$code)->select();

            if (!empty($Images))
            {
                $Pet['hasImg']=1;
                foreach ($Images as $key=>$image)
                {
                    $Images[$key]['ImgUrl']="https://{$_SERVER['HTTP_HOST']}/{$image['url']}";
                }
                $Pet['img']=$Images;
            }
            else
                $Pet['hasImg']=0;

            return json($Pet);
        }else{
            $Radar=\db('find_radar')
                ->alias('f')
                ->join('wyz_users u','u.Id=f.uid')
                ->field('f.*,u.qq,u.phone')
                ->where('f.Id',$Id)->find();

            $code=$Radar['code'];

            $Images=\db('find_img')->where('code',$code)->select();

            if (!empty($Images))
            {
                $Radar['hasImg']=1;
                foreach ($Images as $key=>$image)
                {
                    $Images[$key]['ImgUrl']="https://{$_SERVER['HTTP_HOST']}/{$image['url']}";
                }
                $Radar['img']=$Images;
            }
            else
                $Radar['hasImg']=0;

            return json($Radar);
        }
    }

    public function Confirm(): Json   //确认（领养/找回）【三合一接口】操作
    {
        $type=input('post.type');
        $SafeCode=input('post.SafeCode');
        $id=input('post.id');

        $User=\db('users')->where('SafeCode',$SafeCode)->find();
        $uid=$User['Id'];


        if($type=='pet')
        {
            $Pet=\db('pet')->where('Id',$id)->find();
            if ($Pet['uid']!=$uid)
                return json(['result'=>'error','msg'=>'不是你发布的信息']);

            $SQL=\db('pet')->where('Id',$id)->update([
                'adobted'=>'1'
            ]);
        }else{
            $Radar=\db('find_radar')->where('Id',$id)->find();
            if ($Radar['uid']!=$uid)
                return json(['result'=>'error','msg'=>'不是你发布的信息']);

            $SQL=\db('find_radar')->where('Id',$id)->update([
                'complete'=>'1'
            ]);
        }

        if ($SQL)
            return json(['result'=>'success']);
        else
            return json(['result'=>'error','msg'=>'请勿重复操作']);
    }

    public function Contact(): Json   //联系发布者【三合一接口】
    {
        $List=input('post.List');   //（失物/失主/宠物）信息
        $UserInfo=input('post.UserInfo');   //请求人的信息
        $Id=$List['Id'];
        $uid=$List['uid'];
        $FromUser=\db('users')->where('Id',$uid)->find();   //原发布人信息

        if(!isset($List['thing']) && !isset($List['master']))
        {
            $content="{$UserInfo['college']}-{$UserInfo['major']}专业的{$UserInfo['name']}同学想来找你，因为他在湖工青协志愿服务平台上看到了你发布的“{$List['name']}”,觉得它很可爱，希望能够领养它\n";
            $content=$content."这位同学的QQ为{$UserInfo['qq']}，电话号码为：{$UserInfo['phone']}\n";
            $content=$content."感谢您使用青协志愿平台";

            $sendContent="联系QQ:{$UserInfo['qq']}";

            $data=[
                'phrase1'=>[
                    'value'=>'可爱的'.$List['name']
                ],
                'time5'=>[
                    'value'=>date('Y-m-d H:i:s',time())
                ],
                'name4'=>[
                    'value'=>$UserInfo['name']
                ],
                'thing3'=>[
                    'value'=>$sendContent
                ],
            ];

            $this->sendSubscribeMessage($uid,$data,'pages/mypet/mypet','1MiOiHuWH9hs_kfzcKmXHoPq6F47fkAS0TYtMrrfJzM');

        }else if ($List['thing']==1)
        {
            $content="{$UserInfo['college']}-{$UserInfo['major']}专业的{$UserInfo['name']}同学想来找你，因为他在湖工青协志愿服务平台上看到了你发布的“{$List['title']}”,他觉得这个也许是他丢失的东西，希望能够与你取得联系\n";
            $content=$content."这位同学的QQ为{$UserInfo['qq']}，电话号码为：{$UserInfo['phone']}\n";
            $content=$content."非常感谢您使用志愿平台来帮助别人";


            $data=[
                'thing4'=>[
                    'value'=>$List['title']
                ],
                'time5'=>[
                    'value'=>date('Y-m-d H:i:s',time())
                ],
                'name2'=>[
                    'value'=>$UserInfo['name']
                ],
                'phone_number3'=>[
                    'value'=>$UserInfo['phone']
                ],
                'thing1'=>[
                    'value'=>'他的QQ号码为'.$UserInfo['qq']
                ],
            ];
            $this->sendSubscribeMessage($uid,$data,'pages/mymaster/mymaster','1ajtBXFCwxfq3BVJy-sZqT2Ue9oPzJTRgta7UVp6fKI');



        }elseif ($List['master']==1)
        {
            $content="{$UserInfo['college']}-{$UserInfo['major']}专业的{$UserInfo['name']}同学想来找你，因为他在湖工青协志愿服务平台上看到了你发布的“{$List['title']}”,他觉得这个也许是你丢失的东西，希望能够与你取得联系\n";
            $content=$content."这位同学的QQ为{$UserInfo['qq']}，电话号码为：{$UserInfo['phone']}\n";
            $content=$content."感谢您使用青协志愿平台，为我们的发展提供了支持";

            $data=[
                'thing1'=>[
                  'value'=>$List['title']
                ],
                'date2'=>[
                    'value'=>date('Y-m-d H:i:s',time())
                ],
                'thing5'=>[
                    'value'=>$UserInfo['name']
                ],
                'phone_number6'=>[
                    'value'=>$UserInfo['phone']
                ],
                'thing9'=>[
                    'value'=>'他的QQ号码为'.$UserInfo['qq']
                ],
            ];
            $this->sendSubscribeMessage($uid,$data,'pages/mything/mything','yruMsfqu7IiNzVwRMv8M_efu20GoYKQia9JSNeaaSMw');
        }

        try {
            send_mail($FromUser['qq'].'@qq.com',$FromUser['name'],"湖工青协志愿平台来信",$content);
        }catch (\Exception $e)
        {
            return json(['result'=>'error']);
        }

        return json(['result'=>'success']);
    }

    public function UploadApi() //图片上传接口【三合一接口】
    {
        $code=input('post.code');
        $re=new Request();
        $files=$re->file('img_file');
        if($files){

            $info=$files->validate(['ext'=>'png,gif,jpg,jpeg'])->move('upload');
            //改变一下文件限制


            if($info){
                $url='upload/'.$info->getSaveName();
                $sql=\db('find_img')->insert([
                    'url'=>$url,
                    'code'=>$code
                ]);
                if ($sql)
                {
                    Monitor('上传了失物信息');
                    return json(['result'=>'success','msg'=>$url]);
                }else{
                    return json(['result'=>'error']);
                }

            }else{
                return json(['result'=>'error']);
            }
        }
    }

    public function SubmitItem(): Json    //信息上传接口【三合一】
    {
        $type=input('post.type');
        $SafeCode=input('post.SafeCode');
        $User=\db('users')->where('SafeCode',$SafeCode)->find();

        if (empty($User))
            return json(['result'=>'success','msg'=>'请重新登录']);

        $uid=$User['Id'];

        if ($type=='pet')
        {
            $insert=[
                'name'=>input('post.name'),
                'varieties'=>input('post.varieties'),
                'age'=>input('post.age'),
                'time'=>date('Y-m-d H:i:s',time()),
                'uid'=>$uid,
                'hasReward'=>input('post.hasReward'),
                'reward'=>input('post.hasReward')==1?input('post.reward'):'',
                'code'=>input('post.code'),
                'description'=>input('post.description')
            ];

            $SQL=\db('pet')->insert($insert);
            if ($SQL){
                Monitor('发布了宠物信息',$SafeCode);
                return json(['result'=>'success']);
            }
            else
                return json(['result'=>'error','数据库出错了']);


        }else{
            $insert=[
                'title'=>input('post.title'),
                $type=>'1',
                'content'=>input('post.content'),
                'hasReward'=>input('post.hasReward'),
                'reward'=>input('post.hasReward')==1?input('post.reward'):'',
                'uid'=>$uid,
                'time'=>date('Y-m-d H:i:s',time()),
                'code'=>input('post.code')
            ];
            $radar_id=\db('find_radar')->insertGetId($insert);


            //对tag进行操作
            $tags=explode(",",input('post.tag'));
            $success=0;
            $error=0;
            foreach ($tags as $tag)
            {
                if ($tag=='')
                    continue;

                $tagData=\db('tag')->where('tag_name',$tag)->find();

                //如果数据库已经有这个标签了
                if(!empty($tagData))
                {
                    //就建立关联
                    $sql=\db('radar_tag')->insert([
                        'radar_id'=>$radar_id,
                        'tag_id'=>$tagData['Id']
                    ]);
                    if ($sql)
                    {
                        $success++;
                    }
                    else
                    {
                        $error++;
                    }
                }
                else
                {
                    //先插入这个标签名称再建立关联
                    $tag_id=\db('tag')->insertGetId([
                        'tag_name'=>$tag
                    ]);
                    $sql=\db('radar_tag')->insert([
                        'radar_id'=>$radar_id,
                        'tag_id'=>$tag_id
                    ]);
                    if ($sql)
                    {
                        $success++;
                    }
                    else
                    {
                        $error++;
                    }
                }
            }

            if ($success!=0)
            {
                Monitor('发布了失物信息',$SafeCode);
                return json(['result'=>'success']);
            }
            else
                return json(['result'=>'error','数据库出错了']);
        }

    }

    public function Grade(): Json //成绩获取接口
    {
        //成绩访问接口


        if(!input('post.SafeCode'))
           return json(['code'=>403]);

        $SafeCode=input('post.SafeCode');

        $user=\db('users')->where('SafeCode',$SafeCode)->find();
        $uid = $user['Id'];
        $Sid=\db('sid')->where('uid',$uid)->find();
        //获取用户信息
        //获取输入的年份和学期以确定输出的成绩数据是否为某学期的还是全部

        $hasYearTerm=false;

        if (input('post.year') && input('post.term')) {

            $year=input('post.year');
            $term=input('post.term');
            if ($term=='第一学期'||$term=='1')
                $term=1;
            else
                $term=2;

            $hasYearTerm=true;

            //查找该生平均学分绩点
            $myAvgScoreGpa=\db('avg_score_gpa')->where(['year' => $year, 'term' => $term,'uid'=>$uid])->find();

            $myAvgScoreGpa['courseName']="平均学分成绩";


            $myAvgScoreGpa["order"]=\db('avg_score_gpa')
                ->where(['year' => $year, 'term' => $term])
                ->where('uid','<>',$uid)
                ->where('score','>',$myAvgScoreGpa['score'])
                ->count()+1;

            $scores = \db('grade')->where(['uid' => $uid, 'year' => $year, 'term' => $term])->select();
        } else {
            $scores = \db('grade')->where(['uid' => $uid])->where('is_sum', 0)->select();
        }



        $sum_num=0; //统计不同科目考试最大总人数
        //更新名称
        foreach ($scores as $score) {
            //找出所有比自己成绩高的同学的成绩的个数以确定自己的名次（每一科）
            $num = \db('grade')->where( 'courseCode',$score['courseCode'])
                ->where('uid', '<>', $score['uid'])
                ->where('score', '>', $score['score'])
                ->where(['year' => $score['year'], 'term' => $score['term']])
                ->count();

            //当前科目的总人数
            $nums = \db('grade')->where('courseCode',$score['courseCode'])
                ->where(['year' => $score['year'], 'term' => $score['term']])
                ->count();

            $sum_num=max([$nums,$sum_num]);


            //更新每一科的名次
            \db('grade')->where('uid', $score['uid'])->where('courseCode', $score['courseCode'])->update(['order' => $num + 1]);
        }

        if (input('post.year') && input('post.term')) {
            $year=input('post.year');
            $term=input('post.term');

            if ($term=='第一学期')
                $term=1;
            else
                $term=2;

            $scores = \db('grade')->where(['uid' => $uid, 'year' => $year, 'term' => $term])->select();
        } else {
            $scores = \db('grade')->where(['uid' => $uid])->where('is_sum', 0)->select();
        }

        if ($hasYearTerm){
            $scores[]=$myAvgScoreGpa;
        }

        $arr = [
            'code' => 200,     //状态码为200
            'data' => $scores, //成绩数据
            'sum' => $sum_num
        ];
        Monitor('查询更新了自己的成绩');
        return json($arr);
    }

    public function SubmitBug(): Json //bug或者建议反馈
    {
        $SafeCode=input('post.SafeCode');
        $User=\db('users')->where('SafeCode',$SafeCode)->find();

        if (empty($User))
            return json(['result'=>'success','msg'=>'请重新登录']);

        $uid=$User['Id'];

        $function=input('post.function');
        $description=input('post.description');
        $time=date('Y-m-d H:i:s',time());
        $code=input('post.code');

        $insert=[
            'function'=>$function,
            'description'=>$description,
            'uid'=>$uid,
            'code'=>$code,
            'time'=>$time
        ];

        //发送bug给开发者
        $body="”{$function}“功能出现了新的bug，bug的描述为：<br>{$description}<br>提交时间：{$time}";

        $img=db('find_img')->where('code',$code)->select();
        foreach ($img as $i)
        {
            $body=$body."<img src='https://".$_SERVER['HTTP_HOST']."/".$i['url']."'>";
        }
        send_mail(C('auth_mail'),'志愿服务平台','工程师，出现了新的bug啦！',$body);


        $SQL=\db('bug')->insert($insert);
        if ($SQL){
            Monitor('发表了bug',$SafeCode);
            return json(['result'=>'success']);
        }
        else
            return json(['result'=>'error','数据库出错了']);

    }

    public function AndroidLogin()  //绑定接口
    {
        $username=input('post.username');
        $pwd=input('post.pwd');

        if ($username=='')
            return json(['result'=>'error','msg'=>'请输入账号']);
        if ($pwd=='')
            return json(['result'=>'error','msg'=>'请输入密码']);

        $user=db('users')->where(['username'=>$username,'password'=>md5($pwd)])->find();


        if (!empty($user))
        {
            if($user['active']==0)
                return json(['result'=>'error','msg'=>'账号还未激活，请重新前往邮箱激活']);
            else{
                $SafeCode=GetRandStr(20);
                db('users')->where(['username'=>$username,'password'=>md5($pwd)])->update(['SafeCode'=>$SafeCode]);
                Monitor('通过app登录了!',$SafeCode);
                return json(['result'=>'success','status'=>1,'SafeCode'=>$SafeCode,'msg'=>'登录成功']);
            }
        }else{
            $confirm=\db('users')->where('username',$username)->find();
            if (!empty($confirm))       //如果存在账号，但是密码不对
                return json(['result'=>'error','msg'=>'存在账号，密码错误']);
            else{       //不存在账号就顺便注册
                $qq=input('param.qq');
                if ($qq=='')
                    return json(['result'=>'error','msg'=>'请先输入qq']);
                $SQL=\db('users')->insert(['username'=>$username,'password'=>md5($pwd),'qq'=>$qq]);
                if ($SQL)
                {
                    $ActiveCode=GetRandStr(20);
                    Db::name('users')->where('qq',$qq)->update(['ActiveCode'=>$ActiveCode]);
                    $this->SendActiveMail($username,$qq,$ActiveCode);
                    return json(['result'=>'success','msg'=>'注册成功,请前往邮箱绑定账号后重新进入app，在绑定成功前，您的账号是无效的']);
                }
            }
        }


    }

    public function GetUserData(): Json   //获取用户信息
    {
        if(!input('get.SafeCode') || input('get.SafeCode')==''){
            return json(['result'=>'error']);
        }
        $SafeCode=input('get.SafeCode');
        $UserData=db('users')->where('SafeCode',$SafeCode)->find();

        if(empty($UserData)){
            return json(['result'=>'error']);
        }

        return json($UserData);
    }

    /**
     * 判断某个课程是否在当前查询的周中
     * @param $week int 当前查询的周
     * @param $weekDatum
     * @return false
     */
    private function weekInRange($week, $weekDatum): bool
    {
        //先假设当前查询的日期不在当前课的范围内


        //使用字符串分割，判断有没有逗号，有逗号顺便转化为数组
        $weekData = explode(",", $weekDatum);


        if (count($weekData) <= 1) {

            //此时经过分割以后变量已经成了单元素的数组
            $weekData = $weekData[0];

            //如果是双周，但我查询的数据是单周，就肯定不在里面，返回错误
            if (substr($weekData, -5) === "(双)") {


                if ((int)$week % 2 === 1) {
                    return false;
                }

                //如果确实，先处理一下，使其成为类似1-7或者7的形式
                str_replace("周(双)", "", $weekData);

            }

            //如果是单周，但我查询的数据是双周，就跳过
            if (substr($weekData, -5) === "(单)") {

                if ((int)$week % 2 === 0) {
                    return false;
                }

                //如果确实，先处理一下，使其成为类似1-7或者7的形式
                str_replace("周(单)", "", $weekData);

            }

            /*
             * 到目前，程序已经去除掉了后面的中文字符
             * 也完成了判断单双周
             * 现在只需要判断当前周是否在范围内即可
             */

            $weekData = explode("-", $weekData);

            //如果当前只是7的形式
            if (count($weekData) <= 1) {
                if ((int)$weekData[0] == (int)$week) {
                    return true;
                } else {
                    return false;
                }
            } else {
                //否则当前就是1-7的形式
                //则只需要判断是不是在范围里面就行了
                if ((int)$weekData[0] <= (int)$week && (int)$week <= (int)$weekData[1]) {
                    return true;
                } else {
                    return false;
                }

            }


        } else {
            //否则需要循环判断
            for ($i = 0; $i < count($weekData); $i++) {
                $weekDatum = $weekData[$i];

                //如果是双周，但我查询的数据是单周，就肯定不在里面，返回错误
                if (substr($weekDatum, -5) === "(双)") {

                    if ((int)$week % 2 === 1) {
                        continue;
                    }

                    //如果确实，先处理一下，使其成为类似1-7或者7的形式
                    str_replace("周(双)", "", $weekDatum);

                }

                //如果是单周，但我查询的数据是双周，就跳过
                if (substr($weekDatum, -5) === "(单)") {

                    if ((int)$week % 2 === 0) {
                        continue;
                    }

                    //如果确实，先处理一下，使其成为类似1-7或者7的形式
                    str_replace("周(单)", "", $weekDatum);

                }

                /*
                 * 到目前，程序已经去除掉了后面的中文字符
                 * 也完成了判断单双周
                 * 现在只需要判断当前周是否在范围内即可
                 */

                $weekDatum = explode("-", $weekDatum);

                //如果当前只是7的形式
                if (count($weekDatum) <= 1) {
                    if ((int)$weekDatum[0] == (int)$week) {
                        return true;
                    }
                } else {
                    //否则当前就是1-7的形式
                    //则只需要判断是不是在范围里面就行了
                    if ((int)$weekDatum[0] <= (int)$week && (int)$week <= (int)$weekDatum[1]) {
                        return true;
                    }

                }

            }

            //循环判读无果就肯定是不在这周了
            return false;
        }


    }


    /**
     * 获取课程表信息，按照周查询
     * @return Json
     */
    public function GetTableData(): Json
    {

        $year=input('post.year');
        $term=input('post.term');
        $week=input('post.week');
        $SafeCode=input('post.SafeCode');


        $TableData=\db('users')->alias("u")
            ->leftJoin("wyz_table_json tj","tj.uid=u.Id")
            ->where([
                "u.SafeCode"=>$SafeCode,
                "tj.year"=>$year,
                "tj.term"=>$term,
                "tj.type"=>"1"
                ])->value("tj.table_json");


        $courseList  = json_decode($TableData,true);


        if(is_array($courseList)){
            //初始化课程表
            $TableData=[];
            $TableData[]=[];
            for($i=1;$i<=14;$i++){
                $TableTmp=[];
                for($j=0;$j<=7;$j++){
                    array_push($TableTmp,[]);
                }
                array_push($TableData,$TableTmp);
            }


            foreach ($courseList as $oneCourse){
                //课程所在的周
                $weekDatum = $oneCourse["zcd"];
                $res=$this->weekInRange($week,$weekDatum);

                //如果当前课在查询的周中
                if($res){

                    //星期几？
                    $xqj = $oneCourse["xqj"];

                    //节次？
                    $jcs=$oneCourse["jcs"];

                    $jcs=explode("-",$jcs);

                    if(count($jcs) <= 1){
                        $TableData[(int)$jcs[0]][(int)$xqj]=$oneCourse;
                    }else{
                        for ($i = (int)$jcs[0]; $i <= (int)$jcs[1]; $i++) {
                            $TableData[(int)$i][(int)$xqj] = $oneCourse;
                        }
                    }

                }

            }

            return \json($TableData);

        }else{
            return json(["result"=>"error"]);
        }

    }


}